package thomasweb.spring.data.config;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.flywaydb.core.Flyway;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.autoconfigure.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import thomasweb.spring.data.entity.community.CityRepository;
import thomasweb.spring.data.entity.community.OurCity;


@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef="communityEntityManagerFactory",
		transactionManagerRef="communityTransactionManager",
		basePackageClasses={CityRepository.class})
@EntityScan(basePackageClasses={OurCity.class})
public class CommunityDataSourceConfig {
	
	private final Log LOG = LogFactory.getLog(CommunityDataSourceConfig.class);
	
	@Bean(name="communityDataSource")
	@Primary
	@ConfigurationProperties(prefix="app.datasource.community")
	public DataSource getCommunityDS(){
		return DataSourceBuilder.create().build();
	}
	
	@Bean(name="communityEntityManagerFactory")
	@Primary
	public LocalContainerEntityManagerFactoryBean communityEntityManagerFactory(
			EntityManagerFactoryBuilder builder,
			@Qualifier("communityDataSource") DataSource dataSource){
		 return builder.dataSource(dataSource).packages(OurCity.class).persistenceUnit("community").build();
	}
	
	@Bean(name="communityTransactionManager")
	@Primary
	public PlatformTransactionManager communityTransactionManager(
			@Qualifier("communityEntityManagerFactory") EntityManagerFactory entityManagerFactory){
		return  new JpaTransactionManager(entityManagerFactory);
	}
	
	@Bean
	@Qualifier("communityFlyway")
	@Primary
	public Flyway flywayForCommunityDB(){
		Flyway flyway = new Flyway();
		flyway.setDataSource(getCommunityDS());
		flyway.setBaselineOnMigrate(true);
		flyway.setLocations("classpath:db/migration/community/");
		//ignore checksum
		flyway.setValidateOnMigrate(false);
		flyway.migrate();
		LOG.info("communityFlyway intiated");
		return flyway;
	} 
}
